﻿using AspectCore.Extensions.DependencyInjection;
using AspectCore.Extensions.Autofac;
using Autofac.Extensions.DependencyInjection;
using AspectCore.Configuration;
using AspectCore.DynamicProxy;

namespace Microsoft.Extensions.DependencyInjection
{
    /// <summary>
    /// aspectcore dynamic interceptor
    /// </summary>
    public static class AspectcoreExtension
    {
        /// <summary>
        /// aspectcore 拦截器动态代理服务,默认使用微软自带IOC容器； 
        /// 1：autofac containerbuilder容器、2：aspectcore servicecontext容器、0或其他值：microsoft servicecollection容器; 
        /// 假如要实现代理，请使用ConfigureDynamicProxy或AddDynamicProxy进行具体的操作或条件过滤，继承AbstractInterceptor或AbstractInterceptorAttribute，具体看Aspectcore文档
        /// </summary>
        public static IHostBuilder AddTKAspectcore(this IHostBuilder hostBuilder, int iocType = 0)
        {
            switch (iocType)
            {
                //使用autofac containerbuilder容器
                case 1:
                    hostBuilder.UseServiceProviderFactory(new AutofacServiceProviderFactory(containerBuilder => containerBuilder.RegisterDynamicProxy()));
                    break;
                //使用aspectcore ServiceContext容器
                case 2:
                    hostBuilder.UseServiceProviderFactory(new ServiceContextProviderFactory());
                    break;
                //使用microsoft ServiceCollection容器
                default:
                    hostBuilder.UseServiceProviderFactory(new DynamicProxyServiceProviderFactory());
                    break;
            }
            return hostBuilder;
        }

        /// <summary>
        /// aspectcore 全局增加代理服务
        /// </summary>
        public static IServiceCollection AddDynamicProxy(this IServiceCollection services, Action<IAspectConfiguration> configure = null)
        {
            services.ConfigureDynamicProxy(configure);
            return services;
        }
    }
}
